import browser
from wxauto import WeChat
import time
import random
import re
import pyautogui
import pyperclip

# 初始化微信实例
wx = WeChat()
# 转发群的名称列表
forward_groups = ["YBA的通知分享群8"]

def right_click_forward(target_contact):
    """执行右键转发流程"""
    try:
        current_pos = pyautogui.position()  # 保存当前鼠标位置
        print(f"➡️ 准备转发到 {target_contact}")
        # 步骤1：找到所有小程序图标并定位最后一个
        xcx_locations = list(pyautogui.locateAllOnScreen('xcx.png', confidence=0.7))

        if not xcx_locations:
            print("❌ 未找到任何小程序图标")
            return False

        # 获取最后一个（最新）的小程序图标位置
        last_xcx = max(xcx_locations, key=lambda loc: loc.top)  # 选择y坐标最大的一个（通常在最下方）
        print(f"🔍 找到小程序图标: {last_xcx}")

        # 移动鼠标到小程序位置并右键
        pyautogui.moveTo(pyautogui.center(last_xcx))
        pyautogui.rightClick()
        time.sleep(random.uniform(0.5, 1.0))

        # 步骤2：点击转发菜单（图像识别方案）
        forward_menu = None
        attempts = 0
        # 最多尝试3次识别转发菜单
        while attempts < 3 and not forward_menu:
            print("尝试识别转发菜单...")
            # 调用locateOnScreen进行图像识别
            forward_menu = pyautogui.locateOnScreen('forward_menu.png', confidence=0.7)
            print("识别结果:", forward_menu)
            attempts += 1
            time.sleep(0.5)

        if forward_menu:
            print("找到转发菜单，点击它", forward_menu)
            pyautogui.click(pyautogui.center(forward_menu))
        else:
            # 图像识别失败时使用键盘操作
            print("未找到转发菜单，使用键盘操作", attempts)
            pyautogui.press('down')  # 下移选择菜单项
            time.sleep(0.3)
            pyautogui.press('enter')
        # 鼠标向右移动30像素，向右平移20个像素
        # pyautogui.moveRel(30, 20)  # 鼠标向右移动30像素
        # pyautogui.click()  # 点击转发菜单

        time.sleep(1.5)  # 等待转发窗口打开

        # 步骤3：输入目标联系人
        pyperclip.copy(target_contact)
        pyautogui.hotkey('ctrl', 'v')
        time.sleep(1)
        pyautogui.press('enter')

        # 步骤4：点击发送按钮
        send_button = None
        attempts = 0
        while attempts < 3 and not send_button:
            send_button = pyautogui.locateOnScreen('send_button.png', confidence=0.7)
            print("识别发送按钮:", send_button)
            attempts += 1
            time.sleep(0.5)

        if send_button:
            pyautogui.click(pyautogui.center(send_button))
        else:
            pyautogui.press('enter')  # 回车发送
        print(f"✅ 已转发到 {target_contact}")
        return True

    except Exception as e:
        print(f"❌ 转发失败: {str(e)}")
        return False
    finally:
        pyautogui.moveTo(*current_pos)  # 恢复鼠标位置


def on_message(msg, chat):
    # 提取消息内容并去除 {''} 符号
    raw_content = msg.content
    print(f"Received message: {raw_content}")

    # 忽略系统消息
    if raw_content == "以下为新消息":
        return

    cleaned_content = raw_content.replace("{'", "").replace("'}", "")

    # 匹配关键词并转发(系列, 吊卡,心动特调，星星人，怪味，向往之处）
    if re.search(r'系列|吊卡|心动特调|星星人|怪味|向往之处|比奇堡|crybaby椰青手办|搪胶', cleaned_content):
        print("Detected '' in the message, forwarding...")
        # 获取当前鼠标位置
        current_mouse_pos = pyautogui.position()
        print(f"当前鼠标位置: {current_mouse_pos}")


        if current_mouse_pos != (0, 0):
            success = right_click_forward("bubble通知群")
            if not success:
                print("⚠️ 转发失败，尝试普通发送")
                # wx.SendMsg(cleaned_content, who="bubble通知群")
        else:
            print("⚠️ 无法获取消息位置，使用普通发送")
            # wx.SendMsg(cleaned_content, who="bubble通知群")
    else:
        # wx.SendMsg(cleaned_content, who="bubble通知群")
        print("Message does not contain target keywords, ignoring.")

# 监听来源聊天
wx.AddListenChat(nickname="YBA的通知分享群8【🈲言】", callback=on_message)

# 保持运行
print("👂 开始监听 YBA的通知分享群8...")
wx.KeepRunning()